package com.example.controller;

import com.example.service.UserService;
import com.example.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping
public class LoginController {

//    @GetMapping("login")
//    public String login( Model model){
//        model.addAttribute("keywords","keywords");
//        model.addAttribute("description","description");
//        return "login";
//    }
    @Autowired
    UserService userService;
    @RequestMapping("login")//登录页面展示
    public String login(String refer, Model model, HttpSession session)
    {
        if (refer != null) {
            model.addAttribute("refer",refer);
        }
        if (session.getAttribute("user") != null ){
            return "redirect:/";
        }
        return "login";
    }
    @RequestMapping("loginIn")//别的地方登录，一般用于除非功能后使用，比如添加购物车未登录时弹出，输入后回去
    public String loginIn(String name ,String password , Model model, HttpSession session,String refer){
        User userFromDB = userService.get(name,password);
        if(userFromDB == null){
            String msg = "用户名密码错误，请重试";
            model.addAttribute("msg",msg);
            return "login";
        }
        session.setAttribute("user",userFromDB);
        return "redirect:"+refer;
    }
    @RequestMapping("logout")//同理于LoginIn,能随时登录就能随时登出。
    public String logout(String refer,HttpSession session){
        session.removeAttribute("user");
        if(refer == null){
            refer = "";
        }
        return "redirect:"+refer;
    }

    @RequestMapping("checkLogin")
    @ResponseBody
    public String checkLogin(Model model,HttpSession session){// 一个通常附加在用户行为前的监测，判断是否弹出登录框
        return session.getAttribute("user")!=null?"success":"fail";
    }

}
